package com.bootdo.activiti.controller;

import com.bootdo.common.bootEnum.PurchaseEnum;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.utils.JsonData;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.entity.DataGrid;
import com.bootdo.entity.HistoryProcess;
import com.bootdo.entity.PurchaseApply;
import com.bootdo.entity.PurchaseTask;
import com.bootdo.system.domain.DeptDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.DeptService;
import com.bootdo.system.service.UserService;
import com.bootdo.web.service.PurchaseService;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author wukq
 * @Date: 2020/7/18 16:38
 * @Description: 和gitee上的项目Spring-activiti一起看
 * 目前所有只是看数据，界面没有画。开启流程，流程审批，我发起的流程审批，该我审批的流程列表，
 * 我已审批的流程列表等等
 * <p>
 * 发起审批和审批应该都可以添加附件，附件处理 act_hi_attachment
 * <p>
 * activiti的流程应该是不能随意变通的，流程长，审批多。审批流转多。不同于智慧工匠物资里面的计划审、出库、盘点审批，
 * zhgj的审批流程只能逐步走，不能驳回重新审批。
 * <p>
 * 5：核心API
 * 5.1：ProcessEngine
 * 说明：
 * 1) 在Activiti中最核心的类，其他的类都是由他而来。
 * 2) 产生方式：
 * 在前面看到了两种创建ProcessEngine（流程引擎）的方式，而这里要简化很多，调用ProcessEngines的getDefaultProceeEngine方法时会自动加载classpath下名为activiti.cfg.xml文件。
 * 3) 可以产生RepositoryService
 * 4) 可以产生RuntimeService
 * 5) 可以产生TaskService
 * <p>
 * RepositoryService 管理流程定义
 * RuntimeService 执行管理，包括启动、推进、删除流程实例等操作
 * TaskService 任务管理
 * HistoryService 历史管理(执行完的数据的管理)
 * IdentityService 组织机构管理
 * FormService 一个可选服务，任务表单管理
 * ManagerService
 */
@RestController
@RequestMapping("/act/purchase")
@Transactional(rollbackFor = Exception.class)
public class PurchaseController extends BaseController {
  @Autowired
  private UserService userService;
  @Autowired
  private RepositoryService repositoryservice;//是Activiti的仓库服务类。所谓的仓库指流程定义文档的两个文件：bpmn文件和流程图片。
  @Autowired
  private RuntimeService runtimeService;//执行管理，包括启动、推进、删除流程实例等操作
  @Autowired
  private TaskService taskservice;//任务管理
  @Autowired
  private HistoryService historyService;//历史管理(执行完的数据的管理)
  @Autowired
  private IdentityService identityService;//组织机构管理
  @Autowired
  private PurchaseService purchaseService;
  @Autowired
  private DeptService deptService;

  @RequestMapping(value = "/myPurchase", method = RequestMethod.GET)
  String myPurchase() {
    return "act/purchase/myPurchase";
  }

  /**
   * 开启审批,RestController可以不用@ResponseBody
   */
  @RequestMapping(value = "/startPurchase", method = RequestMethod.POST)
  //@ResponseBody
  JsonData startPurchase(@RequestParam Map<String, Object> map) {
    if (StringUtils.isNullOrEmpty(map.get("itemStr")) || StringUtils.isNullOrEmpty(map.get("total"))) {
      return JsonData.returnJsonDataError(null, "采购物品和采购金额不能为空");
    }
    String itemStr = StringUtils.getMapString(map, "itemStr");//采购物品
    BigDecimal total = new BigDecimal(map.get("total").toString()).setScale(2, RoundingMode.HALF_UP);//采购金额
    UserDO user = ShiroUtils.getUser();
    PurchaseApply purchaseApply = new PurchaseApply();
    purchaseApply.setApplyer(user.getUserId().toString());
    purchaseApply.setTotal(total);
    purchaseApply.setItemlist(itemStr);

    Map<String, Object> variables = new HashMap<>();//工作流配置的参数
    variables.put("starter", user.getUserId());
    //启动流程，获取流程实例id
    ProcessInstance processInstance = purchaseService.startWorkflow(purchaseApply, user.getUserId().toString(), variables);
    if (processInstance != null) {
      System.out.println("流程id" + processInstance.getId() + "已启动");
      return JsonData.returnJsonDataOK();
    } else {
      return JsonData.returnJsonDataOK();
    }
  }

  /**
   * 我发起的采购流程
   * 这里的分页是流程分页，流程分页之后
   * 然后判断userId是不是对的，返回的list数据有可能不够
   * 这个方法里面查的都是还在运行中的流程
   */
  @RequestMapping(value = "/myPurchaseProcess", method = RequestMethod.POST)
  public JsonData myPurchaseProcess() {
    UserDO user = ShiroUtils.getUser();
    List<Map<String, Object>> resultList = new ArrayList<>();

    //查询key为purchase， 的流程实例，还有userId的过滤，查的是ACT_RU_EXECUTION 运行时流程执行实例表
    List<ProcessInstance> processInstancesList = runtimeService.createProcessInstanceQuery().processDefinitionKey("purchase").involvedUser(user.getUserId().toString()).list();
    for (ProcessInstance p : processInstancesList) {
      Map<String, Object> map = new HashMap<>();
      if (p.getActivityId() == null) {//有子流程
        String father = p.getProcessInstanceId();
        String activityId = runtimeService.createExecutionQuery().parentId(father).singleResult().getActivityId();//子流程的活动节点
        String id = runtimeService.createExecutionQuery().parentId(father).singleResult().getId();
        map.put("activityId", activityId);
      } else {
        map.put("activityId", p.getActivityId());
      }
      map.put("businessKey", p.getBusinessKey());
      String activityName = PurchaseEnum.getValues(p.getActivityId());
      map.put("activityName", activityName);
      map.put("executionId", p.getId());
      map.put("processInstanceId", p.getProcessDefinitionId());
      PurchaseApply purchaseApply = purchaseService.getPurchase(Integer.parseInt(p.getBusinessKey()));
      map.put("total", purchaseApply.getTotal());
      map.put("itemList", purchaseApply.getItemlist());
      UserDO userDO = userService.get(Long.parseLong(purchaseApply.getApplyer()));
      map.put("startPersonName", userDO.getUsername());
      resultList.add(map);
    }
    return JsonData.returnJsonDataOK(resultList);
  }

  @RequestMapping(value = "/myPurchaseProcessEnd", method = RequestMethod.POST)
  public JsonData myPurchaseProcessEnd() {
    UserDO user = ShiroUtils.getUser();
    List<Map<String, Object>> resultList = new ArrayList<>();

    //查询key为purchase， 的流程实例，还有userId的过滤，查的是ACT_RU_EXECUTION 运行时流程执行实例表
    List<ProcessInstance> processInstancesList = runtimeService.createProcessInstanceQuery().processDefinitionKey("purchase").involvedUser(user.getUserId().toString()).list();

    return JsonData.returnJsonDataOK();
  }

  /**
   * 未完成的采购审批列表
   * 采购列表
   * 采购员看到的
   * 查的表是act_ru_task，taskService   运行时任务节点表
   */
  @RequestMapping(value = "/purchaseManagerTaskList", method = RequestMethod.POST)
  JsonData purchaseManagerTaskList() {
    DataGrid<PurchaseTask> grid = new DataGrid<>();
    UserDO user = ShiroUtils.getUser();
    if (StringUtils.isNullOrEmpty(user.getDeptId())) {
      return JsonData.returnJsonDataError("部门为空");
    }
    Long deptId = user.getDeptId();
    DeptDO deptDO = deptService.get(deptId);

    if (!deptDO.getName().equals("采购经理")) {
      return JsonData.returnJsonDataError("不是采购经理");
    }

    /*taskCandidateGroup() 用 activiti:candidateGroups 查询，匹配：activiti:candidateGroups="采购经理"
     * taskService.createTaskQuery().taskCandidateUser()也可以用 activiti:candidateUser
     * taskservice.createTaskQuery().taskCandidateOrAssigned() activiti:candidateAssign，都是界面上选择代理对应的属性
     * act_ru_execution 是流程实例
     * 发起人发起流程后,act_run_task里面有一条采购人审批的任务
     * act_ru_variable 流程参数
     */
    List<PurchaseTask> results = new ArrayList<>();
    List<Task> taskList = taskservice.createTaskQuery().taskCandidateGroup("采购经理").list();    //list 可以分页
    long taskNum = taskservice.createTaskQuery().taskCandidateGroup("采购经理").count();
    for (Task task : taskList) {
      PurchaseTask purchaseTask = new PurchaseTask();
      String processInstanceId = task.getProcessInstanceId();//流程实例id
      //singleResult()返回一个结果，runtimeService.createProcessInstanceQuery() 查询运行的流程实例，查的表是act_ru_execution
      // processInstanceId(processInstanceId) 根绝id查询流程实例
      ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
      String businessKey = processInstance.getBusinessKey();//采购表的自增id
      PurchaseApply purchase = purchaseService.getPurchase(Integer.parseInt(businessKey));
      purchaseTask.setApplyer(purchase.getApplyer());
      purchaseTask.setApplytime(purchase.getApplytime());
      purchaseTask.setBussinesskey(purchase.getId());
      purchaseTask.setItemlist(purchase.getItemlist());//采购物品
      purchaseTask.setProcessdefid(task.getProcessDefinitionId());//流程Id   processdefid="purchase:1:167506",act_re_procdef 流程定义数据表
      purchaseTask.setProcessinstanceid(task.getProcessInstanceId());//流程实例id   processinstanceid= 172501,act_ru_execution 运行时流程执行实例表
      purchaseTask.setTaskid(task.getId());//任务id
      purchaseTask.setTaskname(task.getName());//任务名称
      purchaseTask.setTotal(purchase.getTotal());//采购金额
      results.add(purchaseTask);
    }
    grid.setRows(results);
    return JsonData.returnJsonDataOK(grid);
  }

  /**
   * 采购经理审批
   * 参数
   * taskId 任务id
   * purchaseAudit： 审批是否通过，1：是，0：否
   * comment 审批意见
   * attchmentFiles: 附件
   */
  @RequestMapping(value = "/task/purchaseManagerComplete", method = RequestMethod.POST)
  public JsonData purchaseManagerComplete(@RequestParam Map<String, Object> params) {
    UserDO user = ShiroUtils.getUser();
    if (StringUtils.isNullOrEmpty(params.get("taskId")) || StringUtils.isNullOrEmpty(params.get("purchaseAudit"))) {
      return JsonData.returnJsonDataError("参数错误");
    }
    if (StringUtils.isNullOrEmpty(params.get("comment"))) {
      return JsonData.returnJsonDataError("审批意见不能为空");
    }
    String taskId = params.get("taskId").toString();
    String comment = params.get("comment").toString();
    Integer purchaseAudit = Integer.parseInt(params.get("purchaseAudit").toString());
    if (purchaseAudit != 1 && purchaseAudit != 0) {
      return JsonData.returnJsonDataError("参数错误");
    }
    List<Task> list = taskservice.createTaskQuery().taskId(taskId).list();
    if (list == null || list.size() == 0) {
      return JsonData.returnJsonDataError("参数错误");
    }
    Task task = list.get(0);
    //判断身份
    Long deptId = user.getDeptId();
    DeptDO deptDO = deptService.get(deptId);

    if (!deptDO.getName().equals("采购经理")) {
      return JsonData.returnJsonDataError("不是采购经理");
    }
    String processInstanceId = task.getProcessInstanceId();
    ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
    String businessKey = processInstance.getBusinessKey();
    PurchaseApply purchase = purchaseService.getPurchase(Integer.parseInt(businessKey));

    //判断是否审批过,审批过的应该在历史表任务 act_hi_taskinst 里面，不用判断
    //purchaseauditi 是boolean类型，

    Map<String, Object> variables = new HashMap<>();
    variables.put("purchaseAuditi", purchaseAudit == 1 ? true : false);//purchaseAuditi 是界面上flow的流转条件
    variables.put("money", purchase.getTotal());

    if (!StringUtils.isNullOrEmpty(comment)) {
      taskservice.addComment(taskId, task.getProcessInstanceId(), comment);//添加审批意见
    }
    /*
     * taskservice.createAttachment("jpg", taskId, task.getProcessInstanceId(), "test.jpg", "图片", "阿里云图片路径"); //添加附件
     * act_hi_taskinst 和 act_run_task 里面的 主键id相同，都是id,代表task_id，只是act_hi_taskinst 里面的task没有END_TIME,当任务
     * 完成后，act_run_task 里面的task没有了，act_hi_taskinst 有END_TIME,如果调用taskservice.claim()方法， 插入calim时间和assignee代理人
     * 字段
     */
    taskservice.setVariableLocal(taskId, "money", purchase.getTotal());
    taskservice.claim(taskId, user.getUserId().toString());// act_hi_taskinst 的CLAIM_TIME不为空和ASSIGNEE = 136（审批人的ID）
    taskservice.complete(taskId, variables);//审批,还必须要数据，这样act_hi_varinst里面的值就有些冗余了
    return JsonData.returnJsonDataOK("审批成功");
  }

  /**
   * 我发起的采购审批
   */
  @RequestMapping("/myPurchaseList")
  public JsonData myPurchaseList(@RequestParam Map<String, Object> params) {
    UserDO user = ShiroUtils.getUser();
    //startedBy  对应  startUserId 谁发起的，    finish()  对应 ACT_HI_PROCINST 的END_TIME_ IS NOT NULL
    //PROC_INST_ID_ 流程实例id为172501的采购没有结束，所以在ACT_HI_PROCINST历史流程实例表中的END_TIME就是空的
    //ACT_HI_PROCINST 表的主键id和 PROC_INST_ID_ 相同
    List<HistoricProcessInstance> historicProcessInstanceList = historyService.createHistoricProcessInstanceQuery().
            processDefinitionKey("purchase").startedBy(user.getUserId().toString()).list();
    List<HistoryProcess> list = new ArrayList<>();
    for (HistoricProcessInstance item : historicProcessInstanceList) {
      HistoryProcess historyProcess = new HistoryProcess();
      String businessKey = item.getBusinessKey();
      PurchaseApply purchase = purchaseService.getPurchase(Integer.parseInt(businessKey));
      historyProcess.setBusinessKey(businessKey);
      historyProcess.setPurchaseapply(purchase);
      historyProcess.setProcessDefinitionId(item.getProcessDefinitionId());
      historyProcess.setProcessDefinitionId(item.getId());//流程实例id
      list.add(historyProcess);
    }
    Map<String, Object> map = new HashMap<>();
    map.put("list", list);
    return JsonData.returnJsonDataOK(map);
  }


  /**
   * 我已完成采购的审批流程,act_hi_comment里面的comment怎么查
   */
  @RequestMapping("/myAuditList")
  public JsonData myAuditList(@RequestParam Map<String, Object> params) {
    UserDO user = ShiroUtils.getUser();
    List<HistoricProcessInstance> historicProcessInstanceList = historyService.createHistoricProcessInstanceQuery().
            processDefinitionKey("purchase").involvedUser(user.getUserId().toString()).list();
//    processInstanceId 流程实例id，查具体流程
//    List<HistoricProcessInstance> historicProcessInstanceList = historyService.createHistoricProcessInstanceQuery().
//            processInstanceId(processInstanceId).finished().list();
    List<HistoryProcess> list = new ArrayList<>();
    for (HistoricProcessInstance item : historicProcessInstanceList) {
      HistoryProcess historyProcess = new HistoryProcess();
      String businessKey = item.getBusinessKey();
      PurchaseApply purchase = purchaseService.getPurchase(Integer.parseInt(businessKey));
      historyProcess.setBusinessKey(businessKey);
      historyProcess.setPurchaseapply(purchase);
      historyProcess.setProcessDefinitionId(item.getProcessDefinitionId());
      historyProcess.setProcessDefinitionId(item.getId());//流程实例id
      list.add(historyProcess);
    }
    return JsonData.returnJsonDataOK(list);
  }


  /**
   * 所有的采购流程
   */
  @RequestMapping("/allAuditList")
  public JsonData allAuditList(@RequestParam Map<String, Object> params) {
    if (StringUtils.isNullOrEmpty(params.get("processInstanceId"))) {
      return JsonData.returnJsonDataError("参数错误");
    }
    UserDO user = ShiroUtils.getUser();
    List<HistoricProcessInstance> historicProcessInstanceList = historyService.createHistoricProcessInstanceQuery().
            processDefinitionKey("purchase").list();
    List<HistoryProcess> list = new ArrayList<>();
    for (HistoricProcessInstance item : historicProcessInstanceList) {
      HistoryProcess historyProcess = new HistoryProcess();
      String businessKey = item.getBusinessKey();
      PurchaseApply purchase = purchaseService.getPurchase(Integer.parseInt(businessKey));
      historyProcess.setBusinessKey(businessKey);
      historyProcess.setPurchaseapply(purchase);
      historyProcess.setProcessDefinitionId(item.getProcessDefinitionId());
      historyProcess.setProcessDefinitionId(item.getId());//流程实例id
      list.add(historyProcess);
    }
    return JsonData.returnJsonDataOK(list);
  }

  /**
   * 一个采购流程具体的流程任务详情,可以不用流程引擎自带的图，用自己查的流程实例 process 和 流程任务task的 数据展示图
   */
  @RequestMapping("/auditTaskList")
  public JsonData auditTaskList(@RequestParam Map<String, Object> params) {
    if (StringUtils.isNullOrEmpty(params.get("processInstanceId"))) {
      return JsonData.returnJsonDataError("参数错误");
    }
    String processInstanceId = params.get("processInstanceId").toString();
    //查询流程任务，查的act_hi_taskinst表
    List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).list();
    //上面的只有任务，没有发起流程，发起流程在act_hi_proicinst/act_ru_execution中，id都是172501
    List<HistoricProcessInstance> list1 = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).list();
    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put("startProcess", list1.get(0));
    resultMap.put("taskList", list);
    return JsonData.returnJsonDataOK(resultMap);
  }

  /**
   * 财务审批列表
   */
  @RequestMapping("/financialAuditList")
  public JsonData financialAuditList(@RequestParam Map<String, Object> params) {
    UserDO user = ShiroUtils.getUser();
    //判断身份是否是财务
    if (!checkFinancialRole(user)) {
      return JsonData.returnJsonDataError("不是财务");
    }
    List<Task> taskList = taskservice.createTaskQuery().taskCandidateGroup("财务").list();
    long count = taskservice.createTaskQuery().taskCandidateGroup("财务").count();
    List<PurchaseTask> results = new ArrayList<>();
    for (Task task : taskList) {
      PurchaseTask purchaseTask = new PurchaseTask();
      String processInstanceId = task.getProcessInstanceId();//流程实例id
      //singleResult()返回一个结果，runtimeService.createProcessInstanceQuery() 查询运行的流程实例，查的表是act_ru_execution
      // processInstanceId(processInstanceId) 根绝id查询流程实例
      ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
      String businessKey = processInstance.getBusinessKey();//采购表的自增id
      PurchaseApply purchase = purchaseService.getPurchase(Integer.parseInt(businessKey));
      purchaseTask.setApplyer(purchase.getApplyer());
      purchaseTask.setApplytime(purchase.getApplytime());
      purchaseTask.setBussinesskey(purchase.getId());
      purchaseTask.setItemlist(purchase.getItemlist());//采购物品
      purchaseTask.setProcessdefid(task.getProcessDefinitionId());//流程Id   processdefid="purchase:1:167506",act_re_procdef 流程定义数据表
      purchaseTask.setProcessinstanceid(task.getProcessInstanceId());//流程实例id   processinstanceid= 172501,act_ru_execution 运行时流程执行实例表
      purchaseTask.setTaskid(task.getId());//任务id
      purchaseTask.setTaskname(task.getName());//任务名称
      purchaseTask.setTotal(purchase.getTotal());//采购金额
      results.add(purchaseTask);
    }

    return JsonData.returnJsonDataOK(results);//直接返回报错，要将数据分装到一个新的map中去
  }

  /**
   * 财务审批
   */
  @RequestMapping("/financialAudit")
  public JsonData financialAudit(@RequestParam Map<String, Object> params) {
    if (StringUtils.isNullOrEmpty(params.get("taskId"))) {
      return JsonData.returnJsonDataError("参数错误");
    }
    if (StringUtils.isNullOrEmpty(params.get("comment"))) {
      return JsonData.returnJsonDataError("审批意见不能为空");
    }
    if (StringUtils.isNullOrEmpty(params.get("isAudit"))) {
      return JsonData.returnJsonDataError("审批错误");
    }
    Integer isAudit = Integer.parseInt(params.get("isAudit").toString());
    if (isAudit != 1 && isAudit != 0) {
      return JsonData.returnJsonDataError("审批错误");
    }
    UserDO user = ShiroUtils.getUser();
    String comment = params.get("comment").toString();
    //判断身份是否是财务
    if (!checkFinancialRole(user)) {
      return JsonData.returnJsonDataError("不是财务");
    }
    String taskId = params.get("taskId").toString();
    Task task = taskservice.createTaskQuery().taskId(taskId).singleResult();
    if (task == null) {
      return JsonData.returnJsonDataError("任务不存在");
    }
    String processInstanceId = task.getProcessInstanceId();
    ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
    String businessKey = processInstance.getBusinessKey();

    PurchaseApply purchase = purchaseService.getPurchase(Integer.parseInt(businessKey));
    BigDecimal total = purchase.getTotal();

    if (!StringUtils.isNullOrEmpty(comment)) {
      taskservice.addComment(taskId, processInstanceId, comment);//先添加备注
    }

    Map<String, Object> variables = new HashMap<>();
    variables.put("isAudit", isAudit);
    //variables.put("taskId", taskId);//act_hi_varinst 缺少taskId字段，无法关联，直接写了一个name是 taskId的参数，我去
    taskservice.setVariableLocal(taskId, "isAudit", isAudit);//向act_hi_varinstc插入了数据

    taskservice.claim(taskId, user.getUserId().toString());
    taskservice.complete(taskId, variables);//向act_hi_varinstc插入了数据，插入了2编数据


    return JsonData.returnJsonDataOK();
  }

  /**
   * 调整申请列表
   */
  @RequestMapping("/updateApplyList")
  public JsonData updateApplyList(@RequestParam HashMap<String, Object> params) {
    UserDO user = ShiroUtils.getUser();
    String userId = user.getUserId().toString();
    List<Task> list = taskservice.createTaskQuery().processDefinitionKey("purchase").taskCandidateOrAssigned(userId).taskDefinitionKey("updateapply").list();
    List<Map<String, Object>> resultList = new ArrayList<>();
    List<PurchaseTask> plist = new ArrayList<PurchaseTask>();
    for (Task task : list) {
      PurchaseTask vo = new PurchaseTask();
      String instanceid = task.getProcessInstanceId();
      ProcessInstance ins = runtimeService.createProcessInstanceQuery().processInstanceId(instanceid).singleResult();
      String businesskey = ins.getBusinessKey();
      PurchaseApply a = purchaseService.getPurchase(Integer.parseInt(businesskey));
      vo.setApplyer(a.getApplyer());
      vo.setApplytime(a.getApplytime());
      vo.setBussinesskey(a.getId());
      vo.setItemlist(a.getItemlist());
      vo.setProcessdefid(task.getProcessDefinitionId());
      vo.setProcessinstanceid(task.getProcessInstanceId());
      vo.setTaskid(task.getId());
      vo.setTaskname(task.getName());
      vo.setTotal(a.getTotal());
      plist.add(vo);
    }

    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put("list", plist);
    return JsonData.returnJsonDataOK(resultMap);
  }

  /**
   * 调整申请
   */
  @RequestMapping("/modifyApply")
  public JsonData modifyApply(@RequestParam HashMap<String, Object> params) {
    UserDO user = ShiroUtils.getUser();
    if (StringUtils.isNullOrEmpty(params.get("taskId")) || StringUtils.isNullOrEmpty(params.get("isApply"))
            || StringUtils.isNullOrEmpty(params.get("total")) || StringUtils.isNullOrEmpty(params.get("itemList"))) {
      return JsonData.returnJsonDataError("参数缺失");
    }
    String userId = user.getUserId().toString();
    String taskId = params.get("taskId").toString();
    String total = params.get("total").toString();
    String itemList = params.get("itemList").toString();
    Map<String, Object> variables = new HashMap<>();
    Task task = taskservice.createTaskQuery().taskId(taskId).singleResult();
    if (task == null) {
      return JsonData.returnJsonDataError("参数错误");
    }
    boolean isApply = Boolean.parseBoolean(params.get("isApply").toString());
    ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
    if (true == isApply) {
      PurchaseApply purchase = purchaseService.getPurchase(Integer.parseInt(processInstance.getBusinessKey().toString()));
      purchase.setItemlist(itemList);
      purchase.setTotal(new BigDecimal(total));
      purchaseService.updatePurchase(purchase);
    }

    variables.put("updateapply", isApply);
    taskservice.claim(taskId, userId);
    taskservice.complete(taskId, variables);

    if (!StringUtils.isNullOrEmpty(params.get("comment"))) {
      String comment = params.get("comment").toString();
      taskservice.addComment(taskId, processInstance.getProcessInstanceId(), comment);
    }
    return JsonData.returnJsonDataOK();
  }

  /**
   * 审批通过和不通过可以查询 act_hi_procinst,结束的流程实例，里面的end_act_id是结束节点。
   * 已event_2结束的界面是审批不通过的，以event3节点结束的是审批通过的。（忘记给）
   * startedBy 对应的 act_hi_procinst start_act_id用户Id，
   * 里面还有BUSINESS_KEY,可以查详情
   * variableValueLike() 比较String类型
   * variableValueEquals
   * variableValueGreaterThan()
   * variableValueLessThan()
   */
  @RequestMapping("/myPassList")
  public JsonData myPassList(@RequestParam HashMap<String, Object> params) {
    UserDO user = ShiroUtils.getUser();
    String userId = user.getUserId().toString();
    List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().processDefinitionKey("purchase").variableValueEquals("isAudit", 1).list();

    List<HistoricProcessInstance> list2 = historyService.createHistoricProcessInstanceQuery().processDefinitionKey("purchase").unfinished().list();
    List<HistoricProcessInstance> list3 = historyService.createHistoricProcessInstanceQuery().processDefinitionKey("purchase").finished().list();

    List<Map<String, Object>> resultList = new ArrayList<>();
    for (HistoricProcessInstance item : list) {
      Map<String, Object> map = new HashMap<>();
      map.put("processInstanceId", item.getId());
      map.put("startUserId", item.getStartUserId());
      UserDO userDO = userService.get(Long.parseLong(item.getStartUserId()));
      map.put("startUserName", userDO.getUsername());
      map.put("startTime", item.getStartTime());
      map.put("endTime", item.getEndTime());
      map.put("businessKey", item.getBusinessKey());
      PurchaseApply purchase = purchaseService.getPurchase(Integer.parseInt(item.getBusinessKey()));
      map.put("purchase", purchase);
      map.put("name", item.getName());
      resultList.add(map);
    }
    return JsonData.returnJsonDataOK(resultList);
  }

  /**
   * 审批通过的列表
   */
  @RequestMapping("/myNotPassList")
  public JsonData unPassList(@RequestParam HashMap<String, Object> params) {

    return JsonData.returnJsonDataOK();
  }

  /**
   * 审批通过的列表
   */
  @RequestMapping("/detail")
  public JsonData detail(@RequestParam HashMap<String, Object> params) {
    if (StringUtils.isNullOrEmpty(params.get("processInstanceId"))) {
      return JsonData.returnJsonDataError();
    }
    String processInstanceId = params.get("processInstanceId").toString();
    //2）通过流程实例查询所有的(用户任务类型)历史活动
    List<Map<String, Object>> resultList = new ArrayList<>();

    //HistoricActivityInstance 对应act_hi_actinst，一些历史参数，发起审批，审批，网关
    List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).list();
    //去第一条，发起审批
    HistoricActivityInstance historicActivityInstance = list.get(0);
    List<HistoricVariableInstance> list2 = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstanceId).list();
    for (HistoricVariableInstance item : list2) {
      item.getVariableName();
      item.getValue();
    }
    String startPersonId = list2.get(0).getValue().toString();//发起人ID，
    //然后拼接下面的list
    List<HistoricTaskInstance> list1 = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).list();
    for (HistoricTaskInstance item : list1) {
      String taskId = item.getId();
      List<Comment> comment = taskservice.getTaskComments(taskId);
      Map<String, Object> map = new HashMap<>();

      if (comment != null && comment.size() > 0) {
        map.put("comment", comment.get(0).getFullMessage());
      }
      map.put("taskId", taskId);
      map.put("claimTime", item.getClaimTime());
      map.put("assignee", item.getAssignee());
      map.put("endTime", item.getEndTime());
      map.put("Name", item.getName());
      map.put("assign", item.getAssignee());

      resultList.add(map);
    }
    Map<String, Object> starterMap = new HashMap<>();
    starterMap.put("userId", startPersonId);
    resultList.add(0, starterMap);
    HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
    String businessKey = historicProcessInstance.getBusinessKey();
    PurchaseApply purchase = purchaseService.getPurchase(Integer.parseInt(businessKey));
    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put("purchaseMap", purchase);
    resultMap.put("taskList", resultList);
    return JsonData.returnJsonDataOK(resultMap);
  }

  public boolean checkFinancialRole(UserDO user) {
    if (user == null) {
      return false;
    }
    Long deptId = user.getDeptId();
    DeptDO deptDO = deptService.get(deptId);
    if ("财务".equals(deptDO.getName())) {
      return true;
    }
    return false;
  }


}
